package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

func main() {
	router := gin.Default()
	router.Use(Logger())
	//基础
	router.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})

	// 此规则能够匹配/user/john这种格式，但不能匹配/user/ 或 /user这种格式
	//router.GET("/user/:name", func(c *gin.Context) {
	//	name := c.Param("name")
	//	c.String(http.StatusOK, "Hello %s", name)
	//})

	// 但是，这个规则既能匹配/user/john/格式也能匹配/user/john/send这种格式
	// 如果没有其他路由器匹配/user/john，它将重定向到/user/john/
	router.GET("/user/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		message := name + " is " + action
		c.String(http.StatusOK, message)
	})


	// 获取参数get post
	router.POST("/params", func(c *gin.Context) {

		id := c.Query("id") // 是 c.Request.URL.Query().Get("id") 的简写
		page := c.DefaultQuery("page", "0")
		name := c.PostForm("name")
		message := c.DefaultPostForm("message","hello")
		re := fmt.Sprintf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
		c.String(http.StatusOK, re)
	})

	//http重定向
	router.GET("/redirects", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com/")
	})
	//路由重定向
	router.GET("/test", func(c *gin.Context) {
	    c.Request.URL.Path = "/test2"
		router.HandleContext(c)
	})
	router.GET("/test2", func(c *gin.Context) {
	    c.JSON(200, gin.H{"hello": "test2"})
	})
	//路由分组
	v1 := router.Group("/v1")
	{
		v1.GET("/login", func(c *gin.Context) {
		    c.JSON(200, gin.H{"hello": "login"})
		})
		v1.GET("/read", func(c *gin.Context) {
		    c.JSON(200, gin.H{"hello": "read"})
		})
	}
	//自定义中间件，只有定义之后的路由才会用中间件

	router.GET("/middleware", func(c *gin.Context) {
		log.Print("执行前")
		example := c.MustGet("example").(string)
		c.JSON(200, gin.H{
			"message": example,
		})
		log.Print("执行完成")
	})
	router.Run() // listen and serve on 0.0.0.0:8080
}

func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		t := time.Now()

		// Set example variable
		c.Set("example", "12345")

		// before request
		log.Print("进入路由前")
		c.Next()

		// after request

		log.Print("进入路由后")
		latency := time.Since(t)
		log.Print("接口耗时",latency)

		// access the status we are sending
		status := c.Writer.Status()
		log.Println("接口状态",status)
		log.Println("==========================================")
	}
}
